package com.study.spark.scala.chapter07

import scala.collection.mutable

object Scala13_Collection_Method_3{
  def main(args: Array[String]): Unit = {
    // TODO 集合 - 方法 - reduce - fold
    val list1 =List(1,2,3,4)

    // (A1,A1)=>A1
    // list1.reduce()

    // (B,Int)=>B
    // list1.reduceLeft()

    // (A1)((A1,A1),=>A1)
    // list1.fold()
    // (B)((B,Int)=>B)
    // list1.foldLeft()

    // "1234"
    println(list1.foldLeft("")(_ + _))//1234

    val map1 =mutable.Map(
      ("a",2),("b",2),("c",3)
    )

    val map2 =mutable.Map(
      ("a",1),("b",4),("c",2)
    )

    // 两个map的合并
    val map3 = map2.foldLeft(map1)(
      (map, kv) => {
        val key = kv._1
        val cnt = kv._2
        val oldcnt = map.getOrElse(key, 0)
        map.update(key, oldcnt + cnt)
        map
      }
    )
    println(map3)//Map(b -> 6, a -> 3, c -> 5)
  }
}
